package cn.yunyichina.provider.reservation.service.impl;

import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.reservation.component.NoBuilder;
import cn.yunyichina.provider.reservation.dao.ItemDao;
import cn.yunyichina.provider.reservation.dao.OrderDao;
import cn.yunyichina.provider.reservation.entity.Item;
import cn.yunyichina.provider.reservation.entity.ItemRule;
import cn.yunyichina.provider.reservation.entity.Order;
import cn.yunyichina.provider.reservation.service.ItemRuleService;
import cn.yunyichina.provider.reservation.service.OrderService;
import cn.yunyichina.provider.reservation.util.UUIDUtil;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lullaby on 2016/8/30.
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private ItemDao itemDao;

    @Resource
    private NoBuilder noBuilder;

    @Resource
    private ItemRuleService itemRuleService;

//    data: {
//        user_id: widget.isWXweb ? widget.platform.open_id : window.appUserInfo.userId,
//        username: this.refs.person.value,
//        phone: this.refs.tel.value,
//        schedule_date,
//        schedule_period,
//        mechanism_id: _d.mechanism_id,
//        mechanism_name: _d.mechanism_name,
//        dept_id: _d.dept_id,
//        dept_name: _d.dept_name,
//        item_id: this.props.params.id,
//        item_name:_d.name,
//        cost: _d.cost,
//        client_type: widget.isWXweb ? 'WXJSAPI' : 'APP'
//    }

    public Response generateOrder(String params) {
        Response response = new Response();
        Order order = JsonUtils.parseObject(params, Order.class);
        order.setId(UUIDUtil.get32UUID());
        order.setOrderNo(noBuilder.generateOrderNo());

        Item item = itemDao.selectById(order.getItemId());
        if (item == null) {
            throw new RuntimeException("Item does not exist");
        }
        order.setMechanismId(item.getMechanismId());
        order.setMechanismName(item.getMechanismName());
        order.setDeptId(item.getDeptId());
        order.setDeptName(item.getDeptName());
        order.setItemName(item.getName());
        order.setCost(item.getCost().doubleValue());

        order.setOrderStatus(1);
        order.setPayStatus(1);
        order.setIsPayCallback(0);

        Map<String, String> param = new HashMap<>();
        param.put("item_id", order.getItemId());
        ItemRule itemRule = JsonUtils.parseObject(itemRuleService.getItemRuleByItemId(JSON.toJSONString(param)), ItemRule.class);
        if (itemRule != null) {
            if (itemRule.getPayOnlineFlag() == 0) {
                order.setReservationNo(noBuilder.generateReserveNo());
                order.setOrderStatus(2);
            }
        }

        orderDao.insert(order);
        response.setResult(JSON.toJSONString(order));

        //增加一个已经销售数量
        try {
            if (order.getOrderStatus() == 2) {
                itemDao.incSaledCount(order.getItemId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    public Response listOrder(String params) {
        Response response = new Response();

        Order order = JsonUtils.parseObject(params, Order.class);

        PageInfo paginator = JSON.parseObject(params, PageInfo.class);
        paginator.setPageNum(paginator.getPageNum() == null ? PageInfo.DEFAULT_PAGE : paginator.getPageNum());
        paginator.setPageSize(paginator.getPageSize() == null ? PageInfo.DEFAULT_LIMIT : paginator.getPageSize());
        paginator.setTotal(orderDao.selectCount(order));

        List<Order> orders = orderDao.select(order, paginator);
        Map<String, Object> result = new HashMap<>();
        result.put("paginator", paginator);
        result.put("list", orders);
        response.setResult(JSON.toJSONString(result));

        return response;
    }

    public Response detailOrder(String params) {
        Response response = new Response();

        Map<String, String> map = JSON.parseObject(params, Map.class);

        Order param = orderDao.selectByOrderNo(map.get("order_no"));
        response.setResult(JSON.toJSONString(param));

        return response;
    }

    public Response cancelOrder(String params) {
        Response response = new Response();
        Map<String, String> map = JSON.parseObject(params, Map.class);
        Order order = new Order();
        order.setId(map.get("id"));
        order.setOrderStatus(4);
        orderDao.update(order);
        return response;
    }

    public Response updateOrderCallback(String params) {
        Response response = new Response();

        Map<String, String> map = JSON.parseObject(params, Map.class);

        Order order = new Order();
        order.setReservationNo(noBuilder.generateReserveNo());
        order.setId(map.get("id"));
        order.setPayOrderNo(map.get("pay_order_no"));
        order.setPayType(StringUtils.isBlank(map.get("pay_type")) ? null : Integer.valueOf(map.get("pay_type")));
        order.setPayCost(StringUtils.isBlank(map.get("pay_cost")) ? null : Double.valueOf(map.get("pay_cost")));
        order.setPayEndTime(map.get("pay_end_time"));
        order.setOpenId(map.get("open_id"));
        order.setIsPayCallback(1);
        order.setOrderStatus(2);
        order.setPayStatus(3);
        orderDao.update(order);

        //增加一个已经销售数量
        try {
            order = orderDao.selectById(order.getId());
            itemDao.incSaledCount(order.getItemId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    public Response updateOrder(String params) {
        Order order = JsonUtils.parseObject(params, Order.class);
        Response response = new Response();
        orderDao.update(order);
        return response;
    }

}
